<template>
  <div class="pageContent">
    <!-- 顶部 -->
    <div class="top flexAround">
      <div class="top_content">
        <div class="top_content_title">累计计量次数</div>
        <div
          class="top_content_content"
        >{{isNull(parseFloat((this.topInfo.calculateTotal)).toFixed(0))}}次</div>
      </div>
      <div class="top_content">
        <div class="top_content_title">累计计量金额（万元）</div>
        <div
          class="top_content_content"
        >{{isNull(parseFloat((this.topInfo.totalPrice)).toFixed(2))}}</div>
      </div>
      <div class="top_content">
        <div class="top_content_title">本年度计量金额（万元）</div>
        <div
          class="top_content_content"
        >{{isNull(parseFloat((this.topInfo.yearTotalPrice)).toFixed(2))}}</div>
      </div>
    </div>

    <!-- 中间内容 -->
    <div class="content">
      <div class="center flexBetween">
        <div class="center_title">计量清单</div>
        <div class="flexBetweenCenter">
          <div style="margin-right:50px">
            <a-radio-group v-model="radioModel" @change="onChange">
              <a-radio-button value="0">全部</a-radio-button>
              <a-radio-button value="1">2021</a-radio-button>
              <a-radio-button value="2">2020</a-radio-button>
            </a-radio-group>
          </div>
          <div>
            <a-input-search
              placeholder="请输入姓名查询"
              v-model="fullName"
              style="width: 300px"
              @search="onSearch"
            />
          </div>
        </div>
      </div>
      <div class="atable">
        <div style="margin-bottom:15px">
          <a-button type="primary" @click="onAdd" icon="plus">新建计量</a-button>
        </div>
        <!-- 表格选中多少项 -->
        <div style="margin-bottom:20px">
          <a-alert type="info">
            <p slot="description">
              <a-icon type="exclamation-circle" style="color:#1890FF;margin-right:5px" />已选择
              <span style="color:#1890FF;margin:0 5px">{{this.selectedRowKeys.length}}</span>项
              <span style="margin-left:10px">计量金额小计：</span>
              <span style="font-weight:600;color:#000">{{selectTotal}}</span> 元
              <span style="color:#1890FF;margin:0 5px;cursor: pointer;" @click="empty">清空</span>
            </p>
          </a-alert>
        </div>
        <a-table
          :columns="columns"
          :data-source="data"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :pagination="false"
        >
          <span slot="personFinishTotal" slot-scope="text,record">
            <a @click="listModal(record)">附件（{{record.fileList.length}}）</a>
            <!-- {{record}} -->
          </span>
          <span slot="action" slot-scope="text, record">
            <a style="color:#1890FF;margin-right:10px" @click="onEdit(text, record)">编辑</a>
            <a-popconfirm
              title="是否确认删除"
              ok-text="确认"
              cancel-text="取消"
              @confirm="confirm(text)"
              @cancel="cancel"
            >
              <a style="color:#1890FF;margin-right:10px">删除</a>
            </a-popconfirm>
          </span>
        </a-table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination flexBetween">
      <div>共 {{total}} 条记录 第 {{current}} / {{this.configFun.pageNum(Math.ceil((total/pageSize)))}} 页</div>
      <div>
        <a-pagination
          :current="current"
          :page-size-options="pageSizeOptions"
          :total="this.configFun.pageNum(total)"
          show-size-changer
          show-quick-jumper
          :page-size="pageSize"
          @change="pageChange"
          @showSizeChange="onShowSizeChange"
        >
          <template slot="buildOptionText" slot-scope="props">
            <span>{{ props.value }}条/页</span>
            <!-- <span v-if="props.value === '40'">全部</span> -->
          </template>
        </a-pagination>
      </div>
    </div>

    <!-- 对话框 -->
    <div class="amodal">
      <a-modal
        v-model="visible"
        :title="modelTitle"
        @ok="handleOk"
        :maskClosable="false"
        cancelText="取消"
        okText="确认"
        class="aModal"
        :centered="true"
      >
        <!-- width="1000px" -->
        <a-form-model ref="ruleForm" :model="form" v-if="visible" :rules="rules">
          <a-form-model-item ref="name" label="计量名称" prop="name">
            <a-input v-model="form.name" :maxLength="30" placeholder="请输入计量名称" />
          </a-form-model-item>
          <a-form-model-item ref="calculatePrice" label="计量金额" prop="calculatePrice">
            <a-input v-model="form.calculatePrice" placeholder="请输入计量金额" />
          </a-form-model-item>
          <a-form-model-item label="计量日期" required prop="calculateDate">
            <a-date-picker
              v-model="form.calculateDate"
              type="date"
              placeholder="请选择日期"
              style="width: 100%;"
            />
          </a-form-model-item>
          <a-form-model-item label="上传附件" prop="formUpload">
            <a-upload
              name="file"
              accept=".pdf"
              :multiple="true"
              :remove="handleRemove"
              :before-upload="beforeUpload"
              :show-upload-list="false"
            >
              <a-button>
                <a-icon type="upload" />上传文件
              </a-button>
              <div style="color:#ccc">请上传pdf文件</div>
            </a-upload>
            <a-spin :spinning="spinning">
              <div v-for="(item,index) in form.fileInfoList" :key="index" class="pdfList">
                <a-icon type="file-pdf" style="color:#1890ff;margin-right:20px" />
                <span style="margin-right:20px">{{item.name}}</span>
                <a-icon type="delete" class="delete" @click="pdfDelete(item.uid)" />
              </div>
            </a-spin>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </div>

    <!-- 附件列表对话框 -->
    <div class="amodal">
      <a-modal
        v-model="visibleList"
        title="计量凭证附件"
        :maskClosable="false"
        cancelText="取消"
        okText="确认"
        :centered="true"
        :footer="null"
      >
        <div style="min-height:200px">
          <div v-for="(item,index) in pdfList" :key="index" @click="pdfShow(item.fileUrl)">
            <span style="color:#1890ff;cursor:pointer">{{item.fileName}}</span>
          </div>
        </div>
      </a-modal>
    </div>
    <!-- pdf对话框 -->
    <div>
      <a-modal
        v-model="visiblePdf"
        :centered="true"
        :footer="null"
        :maskClosable="false"
        width="1080px"
        :bodyStyle="{textAlign:'center'}"
        v-if="visiblePdf"
        key="modal2"
        class="pdfModal"
      >
        <embed v-if="visiblePdf" width="1000" height="700" :src="this.pdfUrl" type />
      </a-modal>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { uploadOSS } from '@/utils/oss.js'
import { calculateQuery, calculateAdd, calculateEdit, calculateDelete } from '@/api/measurementManage'
import { mapGetters } from 'vuex'
export default {
  data() {
    let formUpload = (rule, value, callback) => {
      if (this.isUpload === false) {
        callback(new Error('请上传文件'))
      } else {
        this.$refs.ruleForm.validateField('formUpload')
        callback()
      }
    }
    return {
      radioModel: '0',
      columns: [
        { title: '名称', dataIndex: 'name', key: 'name', align: 'center' },
        { title: '计量金额（元）', dataIndex: 'calculatePrice', key: 'calculatePrice', align: 'center' },
        { title: '计量日期', dataIndex: 'calculateDate', key: 'calculateDate', align: 'center' },
        {
          title: '计量凭证',
          dataIndex: 'personFinishTotal',
          key: 'personFinishTotal',
          align: 'center',
          scopedSlots: { customRender: 'personFinishTotal' }
        },

        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      data: [],
      current: 1,
      modelTitle: '新建计量',
      pageSize: 10,
      isUpload: false,
      total: 1,
      spinning: false,
      pageSizeOptions: ['5', '10', '20', '30', '40'],
      visible: false,
      visibleList: false,
      visiblePdf: false,
      form: {
        fileInfoList: [],
        calculatePrice: '',
        calculateDate: null,
        packageId: '',
        name: ''
      },
      pdfList: [],
      explain: '',
      selectedRowKeys: [],

      labelCol: { span: 7 },
      wrapperCol: { span: 12 },
      selectTotal: 0,
      textSize: { minRows: 3, maxRows: 6 },
      topData: {},
      yearData: '',
      fullName: '',
      topInfo: {},
      editId: '',
      editPackageId: '',
      pdfUrl: '',
      rules: {
        name: [
          {
            required: true,
            message: '请输入计量名称',
            trigger: 'change'
          }
        ],
        calculateDate: [
          {
            required: true,
            message: '请选择时间',
            trigger: 'change'
          }
        ],
        calculatePrice: [
          {
            required: true,
            message: '请输入计量金额',
            trigger: 'change'
          },
          {
            pattern: new RegExp(/^[0-9]+([.]{1}[0-9]+){0,1}$/),
            message: '请输入整数或小数',
            trigger: 'change'
          }
        ],
        formUpload: [{ required: true, validator: formUpload, trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.getData()
    // this.getQueryTotal()
    // console.log(this.userInfo);
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    // 搜索
    onSearch() {
      // this.current = 1
      this.getTotal()
    },
    // 点击附件
    listModal(record) {
      // console.log(record);

      this.pdfList = record.fileList
      this.visibleList = true
    },
    pdfShow(url) {
      this.pdfUrl = url
      this.visiblePdf = true
    },
    //搜索时获取满足的有多少页
    getTotal(val, current) {
      let size = ''
      let page = ''
      if (val) {
        size = val
      } else {
        size = this.pageSize
      }
      if (current) {
        page = current
      } else {
        page = this.current
      }
      let data = {
        page: this.current,
        size: this.pageSize,
        calculateDate: this.yearData,
        likeName: this.fullName,
        orgId: this.userInfo.orgId
      }

      calculateQuery(data).then((res) => {
        this.total = res.data.data.total
        //   console.log(Math.ceil(this.total/size));
        // console.log(page);
        if (Math.ceil(this.total / size) < page) {
          this.current = 1
        } else {
          this.current = page
        }

        this.pageSize = size
        this.getData()
      })
    },
    // 表格
    getData() {
      let data = {
        page: this.current,
        size: this.pageSize,
        calculateDate: this.yearData,
        likeName: this.fullName,
        orgId: this.userInfo.orgId
      }
      this.data = []
      calculateQuery(data).then((res) => {
        // this.topData.personTotal = res.data.data.personTotal
        // this.topData.recordTotal = res.data.data.recordTotal
        // this.topData.wageTotal = res.data.data.wageTotal
        // console.log(res.data);

        this.topInfo = res.data.data
        res.data.data.calculateVOList.forEach((item, index) => {
          item.key = item.id
        })
        this.data = res.data.data.calculateVOList
        this.total = res.data.data.total
      })
    },
    // 判断isNaN
    isNull(val) {
      if (isNaN(val) == true) {
        return 0
      } else {
        return val
      }
    },
    moment,
    // 切换选项卡
    onChange(e) {
      // console.log(this.radioModel)
      this.current = 1
      this.pageSize = 10
      switch (e.target.value) {
        case '0':
          this.yearData = ''

          this.empty()
          break
        case '1':
          this.yearData = '2021'
          this.empty()
          break
        case '2':
          this.yearData = '2020'
          this.empty()
          break
        default:
          break
      }
      this.getData()
    },

    onEdit(text) {
      this.modelTitle = '编辑计量'
      this.form.name = text.name
      this.form.calculatePrice = text.calculatePrice
      if (text.calculateDate) {
        this.form.calculateDate = moment(text.calculateDate)
      } else {
        this.form.calculateDate = ''
      }

      text.fileList.forEach((item) => {
        item.name = item.fileName
        item.uid = item.id
      })
      this.form.fileInfoList = text.fileList
      this.editId = text.id
      this.editPackageId = text.packageId
      this.form.packageId = text.packageId
      this.visible = true
    },
    // 删除
    onDelete(text) {
      calculateDelete({ id: text.id }).then((res) => {
        this.$message.success('删除成功')
        this.getData()
      })
    },
    confirm(item) {
      // console.log(e);
      this.onDelete(item)
    },
    cancel(e) {
      // console.log(e);
      this.$message.error('取消删除')
    },
    // 确认
    handleOk() {
      if (this.form.fileInfoList.length > 0) {
        this.isUpload = true
      } else {
        this.isUpload = false
      }

      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let data = {
            calculateDate: this.form.calculateDate,
            calculatePrice: this.form.calculatePrice,
            fileInfoList: this.form.fileInfoList,
            name: this.form.name,
            orgId: this.userInfo.orgId,
            packageId: this.form.packageId
          }
          if (this.modelTitle == '新建计量') {
            calculateAdd(data).then((res) => {
              // console.log(res)
              this.$message.success('新建成功')
              this.visible = false
              this.getData()
            })
          } else {
            data.id = this.editId
            calculateEdit(data).then((res) => {
              // console.log(res)
              this.$message.success('编辑成功')
              this.visible = false
              this.getData()
            })
          }
        } else {
          return false
        }
      })
    },
    // 新增
    onAdd() {
      this.modelTitle = '新建计量'
      this.visible = true
      this.spinning = false
      this.form.calculatePrice = null
      this.form.name = null
      this.form.fileInfoList = []
      this.form.calculateDate = null
    },

    onShowSizeChange(current, pageSize) {
      // console.log(current, pageSize)
      this.current = 1
      this.pageSize = pageSize
      this.getTotal(pageSize, this.current)
    },
    pageChange(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.getTotal(pageSize, this.current)
    },
    // 勾选
    onSelectChange(selectedRowKeys) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys
      // console.log( this.selectedRowKeys);
      this.selectTotal = 0
      let _this = this

      this.selectedRowKeys.forEach((item, index) => {
        // let key = item
        // console.log(key,index);
        let total = 0
        this.data.forEach((res) => {
          if (item == res.key) {
            total = res.calculatePrice
          }
        })
        // console.log(_this.data[index]);
        this.selectTotal = this.selectTotal + (total - 0)
        this.selectTotal = parseFloat(this.selectTotal.toFixed(2))
      })
    },
    // 清空
    empty() {
      // console.log(11);

      this.selectedRowKeys = []
      this.selectTotal = 0
    },
    handleRemove(file) {
      // console.log(file.uid)
      this.form.fileInfoList.forEach((item, index) => {
        if (file.uid == item.uid) {
          this.form.fileInfoList.splice(index, 1)
        }
      })
      if (this.form.fileInfoList.length != 0) {
        this.isUpload = true
      } else {
        this.isUpload = false
      }
      // this.form.fileInfoList
    },

    beforeUpload(file) {
      // this.flagUpload=false
      if (this.configFun.pdf(file)) {
        const reader = new FileReader()
        reader.readAsDataURL(file) // 读取图片文件
        this.spinning = true
        reader.onload = (data) => {
          //  console.log(file)
          if (this.modelTitle == '新建计量') {
            this.form.packageId = file.uid
          } else {
            this.form.packageId = this.editPackageId
          }

          this.uploadFile(data.target.result, file.name, file.uid, this.form.packageId)
        }
        this.isUpload = true
        // this.$message.success(`${file.name} 上传成功`, 1)
      } else {
        // this.defaultFileList = []
        // this.flagUpload=true
        this.$message.error('你上传的不是PDF')
        return false
      }

      return false
    },
    uploadFile(base64Data, fileName, fileUid, packageId) {
      let blob = this.dataURLtoBlob(base64Data)
      let dir = 'lw/' + 'measurementManage' + packageId + '/'
      uploadOSS(blob, fileName, dir).then((fileUrl) => {
        // console.log(fileUrl, fileName)
        let obj = { url: fileUrl, name: fileName, uid: fileUid, fileName: fileName, fileUrl: fileUrl }
        // console.log( obj.fileUid );
        this.form.fileInfoList.push(obj)
        this.$message.success(`${obj.name} 上传成功`, 1)
        this.spinning = false
      })
    },
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], {
        type: mime
      })
    },
    pdfDelete(uid) {
      let findVal = this.form.fileInfoList.findIndex((item) => {
        return item.uid === uid
      })
      // console.log(findVal)

      this.form.fileInfoList.splice(findVal, 1)
      if (this.form.fileInfoList.length != 0) {
        this.isUpload = true
      } else {
        this.isUpload = false
      }
    }
  }
}
</script>

<style scoped lang='less'>
.flexAround {
  width: 100%;
}
.atable {
  width: 100%;
}
.top {
  text-align: center;
  color: #555;
  margin-bottom: 20px;
  background: #fff;
  padding: 15px 30px;
}
.center {
  margin-bottom: 20px;
}
.content {
  background: #fff;
  padding: 15px 0px;
  margin-bottom: 15px;
  width: 100%;
}
.top_content {
  flex: 1;
  border-right: 1px solid #ccc;
}
.top_content:last-of-type {
  border: none;
}
.top_content_content {
  color: #000;
  font-size: 30px;
  /* font-weight: 600; */
}
.center_title {
  font-size: 16px;
  color: #000;
  font-weight: 600;
}
::v-deep .ant-alert-with-description .ant-alert-message {
  margin-bottom: 0;
}
::v-deep .ant-alert-with-description.ant-alert-no-icon {
  padding: 4px;
}
p {
  margin: 0;
  padding-left: 20px;
}
.delete:hover {
  color: #1890ff;
  cursor: pointer;
}
.pdfList {
  padding: 5px 10px;
  border: 1px solid #ccc;
  margin: 7px 0px;
}
::v-deep .ant-upload.ant-upload-select {
  width: 100%;
}
::v-deep .ant-modal {
  padding-bottom: 0;
}
.aModal {
  ::v-deep .ant-modal-body {
    max-height: 500px;
    overflow: auto;
  }
}

.aModal {
  ::-webkit-scrollbar {
    width: 7px;
    height: 7px;
    /**/
  }
}
.aModal {
  ::-webkit-scrollbar-track {
    background: #f8f8f8;
    border-radius: 4px;
  }
}
.aModal {
  ::-webkit-scrollbar-thumb {
    background: #ddd;
    border-radius: 4px;
  }
}
</style>
